package com.ruoyi.demo.service;

import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.ruoyi.demo.domain.vo.meetLogVO;
import com.ruoyi.demo.util.DeepSeekV1Util;
import com.ruoyi.demo.util.MinIOUtil;
import com.ruoyi.demo.util.ParaformerUtil;
//import com.ruoyi.demo.util.deepSeekUtil;
import com.ruoyi.system.domain.Agenda;
import com.ruoyi.system.domain.MeetMaterials;
import com.ruoyi.system.mapper.MeetMaterialsMapper;
import com.ruoyi.system.service.IAgendaService;
import com.ruoyi.system.service.IMeetMaterialsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;


@Service
@Slf4j
public class MeetingSummaryService {


    @Autowired
    private DeepSeekV1Util deepSeekV1Util;


    @Autowired
    private IMeetDetailService meetDetailService;

    @Autowired
    private ParaformerUtil paraformerUtil;

    @Autowired
    private IAgendaService  agendaService;

    @Autowired
    private IMeetMaterialsService meetMaterialsService;


    @Autowired
    private MinIOUtil minIOUtil;


    /**
     * 生成会议纪要
     */
    public void generateSummary(MeetMaterials meetMaterials) {
        //获取对应的会议信息
        meetLogVO meetInfo = meetDetailService.selectMeetInFo(meetMaterials.getMeetId());
        meetInfo.setMeetMaterials(meetMaterials);

        // 获取会议的整体内容
        String meetingTitle = meetInfo.getMeet().getTheme();  // 会议主题
        String meetingContent = meetInfo.getMeet().getMeetContent();  // 会议内容
        Date startTime = meetInfo.getMeet().getStartTime();//会议时间
        String roomAddress = meetInfo.getRoom().getRoomAddress();//会议地址
        String userName = meetInfo.getUserList().get(0).getUserName();//会议创建人员

        // 使用 SimpleDateFormat 格式化 Date 对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedStartTime = sdf.format(startTime);

        log.info("会议开始时间: {}", formattedStartTime);

        // 拼接会议的总体信息
        StringBuilder totalMeetingSummary = new StringBuilder();
        totalMeetingSummary.append("会议主题: ").append(meetingTitle).append("\n")
                .append("会议内容: ").append(meetingContent).append("\n")
                .append("会议时间: ").append(formattedStartTime).append("\n")
                .append("会议地点: ").append(roomAddress).append("\n")
                .append("会议创建人员: ").append(userName).append("\n\n");

        // 逐个议程处理
        for (Agenda agenda : meetInfo.getAgendaList()) {

            if("会议签到".equals(agenda.getAgendaTitle())){
                continue;
            }

            // 对应议程的音频文件路径
            String path = "meet/" + meetMaterials.getMeetId() + "/agendaAudio/";
            String audioPath = minIOUtil.generatePresignedUrl(path + agenda.getVoicePath(), 60);
            log.info("audioPath: {}", audioPath);

            // 语音转文本
            String transcript = null;
            try {
                transcript = paraformerUtil.speechToText(audioPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("Transcript for agenda {}: {}", agenda.getAgendaId(), transcript);

            try {
                String agendaTitle = "议程标题 :" + agenda.getAgendaTitle();  // 获取议程标题
                String agendaContent = "议程内容 :" +  agenda.getAgendaContent();  // 获取议程内容
                String userMessage = agendaTitle + "\n" + agendaContent + "\n" + transcript;
                String summary = deepSeekV1Util.generateMeetingSummary(userMessage);



                String agendaSummary = agendaTitle + "\n" + agendaContent + "\n" + "议程纪要: " + summary + "\n\n";
                totalMeetingSummary.append(agendaSummary);  // 将当前议程的纪要内容加入总纪要

                log.info("summary hhhhh jjj for agenda {}: {}", agenda.getAgendaId(), summary);

                // 保存该议程的纪要内容到数据库
                if (summary != null) {

                    //上传到minIO
                    String fileName = minIOUtil.uploadSummaryToMinIO(summary, String.valueOf(meetMaterials.getMeetId()),agenda.getAgendaTitle(),"/agendaSummary/");

                    agenda.setMinutesPath(fileName);
                    // 假设你有一个方法保存议程的纪要内容
                    agendaService.updateAgenda(agenda);
                }
            } catch (NoApiKeyException | InputRequiredException e) {
                e.printStackTrace();
            }
        }
        // 生成总的会议纪要
        String completeMeetingSummary = totalMeetingSummary.toString();

        String summaryPath = minIOUtil.uploadSummaryToMinIO(completeMeetingSummary, String.valueOf(meetMaterials.getMeetId()),meetingTitle,"/summary/");

        meetMaterials.setMinutesPath(summaryPath);

        meetMaterialsService.updateMeetMaterials(meetMaterials);
        // 你也可以保存该会议纪要路径到数据库或其他地方（可选）
        log.info("Meeting summary generated and saved.: {}", completeMeetingSummary);
    }
}
